package com.example.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.api.dto.CourseReq;
import com.example.api.entity.*;
import com.example.api.exception.CustomException;
import com.example.api.service.ICategoryService;
import com.example.api.service.ICourseOrderService;
import com.example.api.service.ICourseService;
import com.example.api.service.IUserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.example.api.dto.ResStatusCode.COURSE_QUERY_ERROR;
import static com.example.api.dto.ResStatusCode.COURSE_QUERY_LIST_ERROR;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author TeacherLi
 * @since 2020-09-06
 */
@RestController
@RequestMapping("/api/course")
public class CourseController extends BaseController{
    private static  final Logger log = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICourseOrderService orderService;


    @PostMapping("/getCourseList")
    @ApiOperation("课程列表查询接口")
    public ResponseEntity<Page<Course>> getCourseList(
            @ApiParam("课程查询条件")
            @RequestBody
            CourseReq courseReq
    ){

        try {
            if(courseReq==null){
                courseReq= new CourseReq();
            }


            //拼接查询条件
            QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
            // 配置返回的字段列表
            queryWrapper.select("id","title","image","sale_count","price");

            //判断类别是 一级还是二级
            Category category = null;

            if(courseReq.getCategoryId()!=null) {
                category = categoryService.getById(courseReq.getCategoryId());
            }

            if(category!=null){

                if(category.getLevel()==1){
                    courseReq.setSubjectId(0);
                }else {
                    courseReq.setSubjectId(category.getId());
                    courseReq.setCategoryId(category.getParentId());
                }
            }else{
                courseReq.setCategoryId(0);
                courseReq.setSubjectId(0);
            }


            Course course = new Course();
            course.setCategoryId(courseReq.getCategoryId()==null ||courseReq.getCategoryId()==0 ?
                    null:courseReq.getCategoryId());
            course.setSubjectId(courseReq.getSubjectId()==null || courseReq.getSubjectId()==0?
                    null:courseReq.getSubjectId());
            course.setTeachType(courseReq.getTeachType()==null || courseReq.getTeachType()==0?
                    null:courseReq.getTeachType());
            course.setPriceType(courseReq.getPriceType()==null || courseReq.getPriceType()==0?
                    null:courseReq.getPriceType());

            queryWrapper.setEntity(course);

            //排序条件
            if(courseReq.getSortType()!=null){

                switch (courseReq.getSortType()){

                    case 1://销量倒序
                        queryWrapper.orderByDesc("sale_count");
                        break;
                    case 2://新品倒序
                        queryWrapper.orderByDesc("create_time");
                        break;
                    case 3://价格倒序
                        queryWrapper.orderByDesc("price");
                        break;
                    case 4://价格升序
                        queryWrapper.orderByAsc("price");
                        break;
                }
            }

            //价格区间
            if(courseReq.getStartPrice()!=null && courseReq.getStartPrice()>0){
                //起始价
                queryWrapper.ge("price",courseReq.getStartPrice());
            }

            if(courseReq.getEndPrice()!=null && courseReq.getEndPrice()>courseReq.getStartPrice()){
                //结束价
                queryWrapper.le("price",courseReq.getEndPrice());
            }

            //分页
            Page<Course> page = new Page<>(courseReq.getPageNo(),courseReq.getPageSize());
            page.setSearchCount(true);

            page = courseService.page(page, queryWrapper);

            return ResponseEntity.ok(page);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw  new CustomException("", COURSE_QUERY_LIST_ERROR.getCode(), COURSE_QUERY_LIST_ERROR.getMessage());
        }

    }

    @GetMapping("/{courseId}")
    @ApiOperation("获取课程详情的接口")
    public ResponseEntity<Course> getCourse(
            @ApiParam("课程ID")
            @PathVariable(value = "courseId",required = true)
            Long courseId){

        try {
            Course course = courseService.getById(courseId);
            if(course!=null){

                //是否购买
                course.setBought(isBuyCourse(courseId,getUser()));

                //所属类别 科目
                Category cate = categoryService.getById(course.getCategoryId());
                Category subject = categoryService.getById(course.getSubjectId());

                course.setCategoryName(cate.getName());
                course.setSubjectName(subject.getName());

                return ResponseEntity.ok(course);
            }else{
                throw new CustomException(courseId+"",COURSE_QUERY_ERROR.getCode(),COURSE_QUERY_ERROR.getMessage());
            }
        } catch (CustomException e) {
            log.error(e.getMessage(),e);
            throw new CustomException(courseId+"",COURSE_QUERY_ERROR.getCode(),COURSE_QUERY_ERROR.getMessage());
        }
    }




}
